package com.hhz.springcloud.alibaba.contriller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.hhz.springcloud.alibaba.myhandler.CustomerBlockHandler;
import com.hhz.springcloud.entites.CommonResult;
import com.hhz.springcloud.entites.Payment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: Rem
 * @CreateDate: 2020/3/18 16:44
 * @Version: 1.0
 */
@RestController
public class RateLimitController {

    @GetMapping("/byResource")
    @SentinelResource(value = "byResource", blockHandler = "handleException")
    public CommonResult byResource() {
        return new CommonResult(200, "按资源名称限流测试OK", new Payment(2020L, "serial001"));
    }

    public CommonResult handleException(BlockException exception) {
        return new CommonResult(444, exception.getClass().getCanonicalName() + "\t 服务不可用");
    }





    /**
     * 配置规则  配置到nacos中      [
       {
           "resource": 资源名称,
           "limitApp": 来源应用,
           "grade": 阀值类型,0代表线程数,1表示qps,
           "count": 单机伐值,
           "strategy": 流控模式,0代表直接,1代表关联,2代表链路,
           "controlBehavior": 流控效果,0表示快速失败,1表示Warm up,2表示排队等候
           "clusterMode": 是否集群
       }
      ]

     [
         {
             "resource": "/rateLimit/byUrl",
             "limitApp": "default",
             "grade": 1,
             "count": 1,
             "strategy": 0,
             "controlBehavior": 0,
             "clusterMode": false
         }
     ]

     */


    @GetMapping("/rateLimit/byUrl")
    @SentinelResource(value = "byUrl")
    public CommonResult byUrl() {
        return new CommonResult(200, "按url限流测试OK", new Payment(2020L, "serial002"));
    }


    @GetMapping("/rateLimit/customerBlockHandler")
    @SentinelResource(value = "customerBlockHandler",
            blockHandlerClass = CustomerBlockHandler.class,
            blockHandler = "handlerException2")
    public CommonResult customerBlockHandler() {
        return new CommonResult(200, "按客戶自定义", new Payment(2020L, "serial003"));
    }
}